iOS Push Notifications
Here you will learn how to set up all the Group Link iOS SDK functions to support Push Notifications in your application.
Step 1 - Activate the Push Notification Entitlement
On the Signing & Capabilities tab of your target settings, click on the “+ Capability” button, and add the capability Push Notification.
Signing & Capabilities page
Push Notification Capability Screen
Enable Required background mode
The Group Link framework Push Notification support needs the Remote Notification permission inside the Background Modes entitlement to work properly.
Step 2 - Asking for Permission
Now, to ask the user the permission to show notifications, below is the code of how to implement this function.
Swift Implementation - With Badges
let center = UNUserNotificationCenter.current()
func requestNotification() {
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if let error = error {
print("Error asking for notifications: \(error)")
}
print("user granted notification")
// Enable or disable features based on the authorization.
}
}
Swift Implementation - Without Badges
let center = UNUserNotificationCenter.current()
func requestNotification() {
center.requestAuthorization(options: [.alert, .sound]) { granted, error in
if let error = error {
print("Error asking for notifications: \(error)")
}
print("user granted notification")
// Enable or disable features based on the authorization.
}
}
Objective-C Implementation
- (void)askNotificationPermission {
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// Enable or disable features based on authorization.
}];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
Call this function anywhere in your app. In the next example, we will use the application start.
SwiftUI Implementation
@main
struct Group_Link_SettingsApp: App {
init() {
self.requestNotification()
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
UIKit Implementation
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
self.requestNotification()
return true
}
}
Objective-C Implementation
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self askPermission];
return YES;
}
Step 3 - Register for Push Notifications
Next, you have to implement the iOS UIApplication.shared.registerForRemoteNotifications() inside the didFinishLaunchingWithOptions function on your AppDelegate file, if you are using SwiftUI to develop, you will need to use the UIApplicationDelegateAdaptor to implement.
Swift Implementation
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
UIApplication.shared.registerForRemoteNotifications()
return true
}
}
@main
struct Group_Link_SettingsApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
UIKit Implementation
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
UIApplication.shared.registerForRemoteNotifications()
return true
}
}
Objective-C Implementation
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[application registerForRemoteNotifications];
return YES;
}
Step 4 - Setting User Notifications didReceive
To receive notifications and click events from our dashboard, you need to set up the UNNotifications didReceive method inside your AppDelegate, you can follow the example below.
First, you need to insert and conform with the UNUserNotificationCenterDelegate on your AppDelegate class
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
// YOUR APP DELEGATE CODE
}
With the UNUserNotificationCenterDelegate you can call the userNotificationCenter didReceive method and insert the GLNotificationDidReceive from our SDK, just pass the center and the response on the method parameters.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
GroupLinkSDK.GLNotificationDidReceive(center, didReceive: response)
}
Step 5 - Getting Push Notifications Token
With these two implementations, iOS will return the random device token to your application, which will be used to send a notification to the device. To get this token, you will need to implement another UIApplicationDelegate function, the didRegisterForRemoteNotificationsWithDeviceToken in case the user accepts the permission and didFailToRegisterForRemoteNotificationsWithError in case the user denies the permission.
If the user accepts the permission, you will call the sendNotificationToken function from the Group Link SDK.
Swift Implementation
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
GroupLinkSDK.sendNotificationToken(token)
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Error getting notification token: \(error)")
}
Objective-C Implementation
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSUInteger dataLength = deviceToken.length;
if (dataLength == 0) {
return;
}
const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
NSMutableString *token = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[token appendFormat:@"%02x", dataBuffer[i]];
}
[GroupLinkSDK sendNotificationToken:token];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"Error getting token:%@", error);
}
Step 6 - Setting Push Notifications Extension
To receive the notifications KPIs for your application, you will need to set up the notification extension in your app. To set up, just follow the guide below.
Setting Notification Service Extension
First, you have to create a Notification Service Extension, it's simple, just go to your project file General tab, and in the targets menu, click on the plus sign.
Extensions plus sign inside your project
After clicking, a window will appear to select the extension type you want, Apple will provide a variety of extensions to your application, but you will choose the Notification Extension Service, this extension's purpose is to implement rich notifications, such as notifications with images, URLs, and more data.
Notification Service Extension Menu
Xcode will ask if you want to debug the Notification Service Extension instead of your application. Click on Activate or Cancel to continue debugging your application.
Debug Extension screen
And finally, just import the GroupLinkSDK framework inside the Notification Service swift file and insert the isGroupLinkNotification condition below the bestAttemptContent declaration, an example file will be below.
import UserNotifications
import GroupLink
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if !GroupLinkNotifications.isGroupLinkNotification(request: request, contentHandler: contentHandler, bestAttemptContent: bestAttemptContent) {
if let bestAttemptContent = bestAttemptContent {
bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
contentHandler(bestAttemptContent)
}
}
}
override func serviceExtensionTimeWillExpire() {
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
The method isGroupLinkNotification returns a bool, if it returns false, you can implement another push notification service, like OneSignal or Firebase.
Setting up the Notification didReceive Method
To receive the open notification KPI, you need to set up the didReceive
method from UNUserNotificationCenterDelegate
within your application. It is recommended to inherit this delegate in your AppDelegate
class. By implementing this method, you can handle the received notifications and track the open notification KPI accordingly.
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
GroupLinkNotifications.GLNotificationDidReceive(center, didReceive: response)
}
}
As shown in the code above, the delegate contains the didReceive
method to handle push notification opening calls. Within this function, you simply need to call the GroupLinkNotifications.GLNotificationDidReceive
function, passing the center
and response
as parameters. This allows you to handle and process the received push notification accordingly.